package com.link.linkupjavaweb.controller.admin;

import com.link.linkupjavaweb.common.Constants;
import com.link.linkupjavaweb.common.Result;
import com.link.linkupjavaweb.dto.UserManageDTO;
import com.link.linkupjavaweb.entity.Admin;
import com.link.linkupjavaweb.entity.User;
import com.link.linkupjavaweb.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * 管理员-用户管理Controller
 */
@Controller
@RequestMapping("/admin/user")
public class UserManageController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户管理页面
     */
    @GetMapping("/list")
    public String listPage(HttpSession session, Model model) {
        Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
        if (admin == null) {
            return "redirect:/admin/login";
        }
        
        model.addAttribute("admin", admin);
        return "admin/user/list";
    }
    
    /**
     * 获取用户列表（分页）
     */
    @GetMapping("/data")
    @ResponseBody
    public Result<Map<String, Object>> getUserList(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size,
            @RequestParam(required = false) String keyword,
            HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            Map<String, Object> data = userService.getUserList(page, size, keyword);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 添加用户
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<User> addUser(@RequestBody UserManageDTO userDTO, HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            User user = userService.addUser(userDTO);
            return Result.success("添加成功", user);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新用户
     */
    @PostMapping("/update")
    @ResponseBody
    public Result<String> updateUser(@RequestBody UserManageDTO userDTO, HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            boolean success = userService.updateUser(userDTO);
            if (success) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除用户
     */
    @PostMapping("/delete/{userId}")
    @ResponseBody
    public Result<String> deleteUser(@PathVariable Long userId, HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            boolean success = userService.deleteUser(userId);
            if (success) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除失败：" + e.getMessage());
        }
    }
    
    /**
     * 更新用户状态（禁用/启用）
     */
    @PostMapping("/status/{userId}/{status}")
    @ResponseBody
    public Result<String> updateUserStatus(
            @PathVariable Long userId, 
            @PathVariable Integer status,
            HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            boolean success = userService.updateUserStatus(userId, status);
            if (success) {
                return Result.success(status == 0 ? "已启用" : "已禁用");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            return Result.error("操作失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取单个用户信息
     */
    @GetMapping("/detail/{userId}")
    @ResponseBody
    public Result<User> getUserDetail(@PathVariable Long userId, HttpSession session) {
        try {
            Admin admin = (Admin) session.getAttribute(Constants.SESSION_ADMIN);
            if (admin == null) {
                return Result.error("请先登录");
            }
            
            User user = userService.getUserById(userId);
            if (user != null) {
                return Result.success(user);
            } else {
                return Result.error("用户不存在");
            }
        } catch (Exception e) {
            return Result.error("获取失败：" + e.getMessage());
        }
    }
}

